import { defineStore } from 'pinia';
import pinia from '@/store/install';

const useMainStore = defineStore('main', {
  state: () => ({
    loading: false,
    token: '',
    currentScale: 0,
    userInfo: {
      username: '', // 用户名
      realname: '', // 真实姓名
      sex: '', // 性别
      phone: '', // 电话
      email: '', // 邮箱
      birth: '', // 出生日期
      avantor: '', // 头像
    },
  }),
  getters: {
    getUsername: (state) => state.userInfo?.username,
    getToken: (state) => state.token,
    getCurrentScale: (state) => state.currentScale,
  },
  // persist: {
  //   enabled: true,
  //   strategies: [
  //     {
  //       storage: localStorage,
  //     },
  //   ],
  // },
});

// 数据持久化
// 1. 保存数据
const instance = useMainStore(pinia);
instance.$subscribe((_, state) => {
  localStorage.setItem(
    'login-store',
    JSON.stringify({
      ...state,
    }),
  );
});
// 2. 获取保存的数据，先判断有无，无则用先前的
const old = localStorage.getItem('login-store');
if (old) {
  instance.$state = JSON.parse(old);
}

export { useMainStore };
